﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
public class TheadedWorker
{
    public int idleTime = 1;
    public BaseJob curJob = null;
    public AutoResetEvent waitEvent;
    public bool m_startLoop = false;
    public bool m_canFinish = false;

    public int JobCount = 0;
    public TheadedWorker()
    {
        Reset();
    }
    public void Reset()
    {
        curJob = null;
        waitEvent = new AutoResetEvent(false);
    }
    public void CancelJob()
    {

    }
    //TD: ThreadedStreamBuffer     
    public void SetJobFetch(Queue<BaseJob> fetchList)
    {

    }

    public void StartWorkerLoop()
    {
        m_startLoop = true;
        m_canFinish = false;
        JobCount = 0;
        ThreadPool.QueueUserWorkItem(WorkLoopInternal);
    }
    public void WaitDone()
    {
        m_canFinish = true;
        waitEvent.WaitOne();
    }
    private void WorkLoopInternal(object arg)
    {
        bool willLoop = m_startLoop;
        while (willLoop)
        {
            int curCount = 0;
            lock (ParallelTask.g_JobsLocker)
            {
                curCount = ParallelTask.g_Jobs.Count;
                willLoop = !(m_canFinish && curCount == 0);

            }
            if (!willLoop)
            {
                break;
            }
            else
            {
                BaseJob job = null;
                lock (ParallelTask.g_JobsLocker)
                {
                    if (ParallelTask.g_Jobs.Count > 0)
                    {
                        job = ParallelTask.g_Jobs.Dequeue();
                    }
                }

                if (job != null)
                {
                    job.Excute(this);
                    JobCount++;
                }
                else
                {
                    Thread.Sleep(idleTime);
                }
            }

        }

        waitEvent.Set();
        UnityEngine.Debug.Log("This Worker have done  " + JobCount + " Jobs");
    }
    public int GetFinishJobCount()
    {
        return JobCount;
    }
}

